import axios from 'axios'
import { delSaveUserInfo } from "@/utils/storageUtil"
import { Toast } from 'antd-mobile'
import eventBus from './eventBus';

let navigate;
eventBus.$on((propsObj) => {
    navigate = propsObj
}, 'axiosInterceptorsFun')

axios.defaults.withCredentials = true
const service = axios.create({
    baseURL: "https://miot.aidong.me", // 测试IPhttps://miot.51aidong.com--https://miot.aidong.me
    timeout: 30000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
    Toast.show({
        icon: 'loading',
        maskClickable: false,
        content: '',
        duration: 0,
    });
    config.headers['authorization'] = sessionStorage.getItem("aidong:authorization") || null;

    // Do something before request is sent
    config.withCredentials = true;

    config.headers['Content-Type'] = 'application/json;charset=UTF-8';

    return config
}, error => {
    Promise.reject(error)
})

service.interceptors.response.use(
    response => {
        const res = response.data;
        Toast.clear();
        if (res.status === 5000) {
            delSaveUserInfo();
            navigate && navigate("/main", { replace: true })
        }
        return res
    },
    error => {
        Toast.clear();
        return Promise.reject(error)
    })

export default service